import scopt.test.common
from scopt.mpu.business.core.handlers import compound_request
from scopt.mpu.business.devel.handlers import echo


class CompoundMessageTest(scopt.test.common.ScoptTest):
    def test_basic_compound(self):
        echo_request_1 = self.request(echo.echo)
        echo_request_1['reqh']['version'] = '0.1'
        echo_request_1['reqh']['message_id'] = 'msg_id_1'

        echo_request_2 = self.request(echo.echo)
        echo_request_2['reqh']['version'] = '0.1'
        echo_request_2['reqh']['message_id'] = 'msg_id_2'
        c_request = self.request(compound_request.handle)

        echo_request_1['reqd']['text'] = 'TXT_1'
        echo_request_2['reqd']['text'] = 'TXT_2'
        c_request['reqd'] = [echo_request_1, echo_request_2]

        c_response = self.send_request(c_request)
        response_0 = c_response['resd'][0]
        response_1 = c_response['resd'][1]
        self.assertEqual(len(c_response), 2)
        self.assertEqual(response_0['resd']['text'], '0.1: TXT_1')
        self.assertEqual(response_1['resd']['text'], '0.1: TXT_2')
        self.assertIsNotNone(response_0['resh']['note'])

    def test_substitute_compound_by_index(self):
        echo_request_1 = self.request(echo.echo)
        echo_request_1['reqh']['version'] = '0.1'
        echo_request_1['reqh']['message_id'] = 'msg_id_1'
        echo_request_1['reqd']['text'] = 'TXT_1'

        echo_request_2 = self.request(echo.echo)
        echo_request_2['reqh']['version'] = '0.1'
        echo_request_2['reqh']['message_id'] = 'msg_id_2'
        echo_request_2['reqd']['text'] = '${[0].resd.text}'

        c_request = self.request(compound_request.handle)
        c_request['reqd'] = [echo_request_1, echo_request_2]

        c_response = self.send_request(c_request)
        response_0 = c_response['resd'][0]
        response_1 = c_response['resd'][1]
        self.assertEqual(response_0['resd']['text'], '0.1: TXT_1')
        self.assertEqual(response_1['resd']['text'], '0.1: 0.1: TXT_1')
        self.assertEqual(len(c_response), 2)

    def test_substitute_compound_by_key(self):
        echo_request_1 = self.request(echo.echo)
        echo_request_1['reqh']['version'] = '0.1'
        echo_request_1['reqh']['message_id'] = 'msg_id_1'
        echo_request_1['reqd']['text'] = 'TXT_1'

        echo_request_2 = self.request(echo.echo)
        echo_request_2['reqh']['version'] = '0.1'
        echo_request_2['reqh']['message_id'] = 'msg_id_2'
        echo_request_2['reqd']['text'] = '${msg_id_1.resd.text}'

        c_request = self.request(compound_request.handle)
        c_request['reqd'] = [echo_request_1, echo_request_2]

        c_response = self.send_request(c_request)
        response_0 = c_response['resd'][0]
        response_1 = c_response['resd'][1]
        self.assertEqual(response_0['resd']['text'], '0.1: TXT_1')
        self.assertEqual(response_1['resd']['text'], '0.1: 0.1: TXT_1')
        self.assertEqual(len(c_response), 2)
